import {
    AbstractBookCrawler,
    BasicBook,
    BasicChapter,
    Book,
    request,
    SearchBookResult,
    BookCrawlerTest,
    BookSource,
    encodeUrl,
    getPathFromUrl,
    htmlToString,
} from '../../common/common_node.js'

class BookCrawler extends AbstractBookCrawler {
    options = {decoder: 'gbk'}

    async searchBook(keyword, pageNum) {

        const res = await request(`${this.source.searchBaseUrl}/modules/article/search.php?searchkey=${encodeUrl(keyword, 'gbk')}`, {
            ...this.options,
            method: "post"
        });

        const $ = await res.doc();

        const bookArr = [];
        const introduce = $('.introduce');
        if (introduce.length > 0) { // 详情页
            bookArr.push(new BasicBook({
                name: introduce.find('h1').text(),
                author: introduce.find('.bq span a').text(),
                path: getPathFromUrl(res.url),
            }))
        } else { // 搜索结果页
            const trArr = $('table.grid tbody tr').eq(0).nextAll();
            trArr.each((i, e) => {
                const tdArr = $(e).find('td');
                bookArr.push(new BasicBook({
                    name: tdArr.eq(0).text(),
                    author: tdArr.eq(2).text(),
                    path: getPathFromUrl(tdArr.eq(0).find('a').attr('href'))
                }));
            });
        }

        let pages = 1;
        const pagestats = $('#pagestats');
        if (pagestats.length > 0) {
            pages = Number.parseInt(pagestats?.text().split("/")[1]);
        }

        return new SearchBookResult({
            pageNum: pageNum,
            pages: pages,
            keyword: keyword,
            bookList: bookArr
        });
    }

    async bookDetails(path) {

        let $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();

        const introduce = $('.introduce');

        return new Book({
            name: introduce.find('h1').text(),
            author: introduce.find('.bq span a').text(),
            path: path,
            intro: introduce.find('.jj').text(),
            coverUrl: this.source.bookBaseUrl + $('.catalog1 .pic img').attr('src'),
            type: $('.catalog1 p').first().find('a').last().text()
        });
    }

    async bookCatalog(path) {

        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();
        const chapters = $('.ml_list ul li a');
        let catalog = [];
        chapters.each(function (i, elem) {
            const item = $(elem);
            catalog.push(new BasicChapter({
                index: i,
                title: item.text(),
                path: path + item.attr("href")
            }));
        });
        return catalog;
    }

    async chapterContent(path) {

        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();
        return htmlToString($("p.articlecontent").html());
    }
}

const source = {
    "id": "cnbook/2",
    "name": "烈火中文网",
    "portalUrl": "https://www.liehuozw.com",
    "searchBaseUrl": "https://www.liehuozw.com",
    "bookBaseUrl": "https://www.liehuozw.com",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true,
    keyword: "迷踪奸影",
}).run();

